package controllers

import (
	"github.com/astaxie/beego"
	"strings"
	"nway_dsr/dsr/models"
	"nway_dsr/dsr/libs"
	"strconv"
)

type LoginController struct {
	BaseController
}

//登录
func (self *LoginController) LoginIn() {
	//beego.ReadFromRequest(&self.Controller)
	if self.isPost() {

		username := strings.TrimSpace(self.GetString("username"))
		password := strings.TrimSpace(self.GetString("password"))

		if username != "" && password != "" {
			user, err := models.AdminGetByName(username)
			flash := beego.NewFlash()
			if err!=nil {
				flash.Error("没有该账号")
			}else {
				salt:=strings.TrimSpace(user.Salt)
				if  user.Password != libs.Md5([]byte(password+salt)) {
					flash.Error("帐号或密码错误")

				}else {
					//加密
					authkey := libs.Md5([]byte(self.getClientIp() + "|" + user.Password + user.Salt))
					self.Ctx.SetCookie("auth123", strconv.FormatInt(user.Id,10)+"|"+authkey, 7*86400)//写入缓存
					self.redirect(beego.URLFor("BaseController.Index"))
				}
			}
		}
	}
	self.TplName = "login/login.html"
}

//登出
func (self *LoginController) LoginOut() {
	self.Ctx.SetCookie("auth123", "")
	self.redirect(beego.URLFor("LoginController.LoginIn"))
	//self.ajaxMsg("需要登录",MSG_ERR)
}
